package com.carassistant.beta.phone.adapter;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.carassistant.beta.R;
import com.carassistant.beta.db.DBData;

public class FavoriteAdapter extends BaseAdapter{
	private ArrayList<ContentValues> allFavorites; 
	private Context mContext;  
	private int[] numbers = new int[]{R.drawable.i01, R.drawable.i02, R.drawable.i03, R.drawable.i04, 
			R.drawable.i05, R.drawable.i06};
	
	public FavoriteAdapter(Activity mContext, ArrayList<ContentValues> allFavorites){
		this.allFavorites = allFavorites;
		this.mContext = mContext; 
	} 
	
	public void refresh(ArrayList<ContentValues> favs){ 
		this.allFavorites = favs;
		this.notifyDataSetChanged();
	}
	
	@Override
	public int getCount() {
		return 6;
	}

	@Override
	public Object getItem(int position) { 
		if (allFavorites != null && allFavorites.get(position) != null) {
			return allFavorites.get(position).getAsString(DBData.PHONE_NUMBER);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) { 
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(R.layout.phone_favorite_item, null); 
		}
		
		ImageView favId = (ImageView) convertView.findViewById(R.id.favoriteId);
		TextView favName = (TextView) convertView.findViewById(R.id.favoriteName);
		TextView favNum = (TextView) convertView.findViewById(R.id.favoriteNumber);
		ImageView favAdd = (ImageView) convertView.findViewById(R.id.addIcon);
		
		favId.setImageResource(numbers[position]); 
		
		if (allFavorites != null) {
			for(ContentValues cv : allFavorites){
				int id = cv.getAsInteger(DBData.PHONE_ID);
				if (id == position) {
					favAdd.setVisibility(View.GONE);
					String name = cv.getAsString(DBData.PHONE_CONTACT_NAME);
					String number = cv.getAsString(DBData.PHONE_NUMBER);
					
					favName.setText(name);
					favNum.setText(number);
					convertView.setTag(number); 
					return convertView;
				}
			}   
		}  
		favAdd.setVisibility(View.VISIBLE);
		favName.setText("");
		favNum.setText("");
		convertView.setTag(null); 
		return convertView;
	}

}
